package com.dingding.nettyserver.core.queue.listener;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.dingding.common.core.push.pushmsg.TcpPushPack;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.nettyserver.core.scanner.Invoker;
import com.dingding.nettyserver.core.scanner.InvokerHoler;
import com.dingding.nettyserver.core.util.LogKit;

/**
 * @Description tcp推送的监听
 * @author fengshuonan
 * @date 2016年11月30日 下午11:48:42
 */
public class NettyPushListener implements MessageListener {

	private Logger log = Logger.getLogger(NettyPushListener.class);

	@Override
	public Action consume(Message message, ConsumeContext context) {

		String content = null;
		
		//获取推送消息
		try {
			content = new String(message.getBody(),"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			LogKit.error("解析消息队列中的字节码出错！",e1);
		}

		log.info("准备推送消息,消息内容为：" + content);
		
		try {

			//解析字符串形式的推送消息
			TcpPushPack tcpPushPack = JSONUtil.parseObject(content, TcpPushPack.class);
			
			//执行tcp推送
			Invoker invoker = InvokerHoler.getInvoker(
					tcpPushPack.getBizType(), tcpPushPack.getModular(), tcpPushPack.getCmd());
			
			if(invoker == null){
				LogKit.info("找不到该推送的命令执行器！");
				return Action.CommitMessage;
			}else{
				Object result = invoker.invoke(tcpPushPack);
				return (Action) result;
			}
			
		} catch (Exception e) {
			LogKit.error("推送消息过程中失败！错误原因：",e);
			return Action.CommitMessage;
		}
	}
}
